import React, { Component } from 'react'
import Tab from './components/Tab'
import Form from './components/Form'
import List from './components/List'

export default class App extends Component {
  state = {
    tabs: [
      {
        id: 1,
        name: '热度',
        type: 'hot',
      },
      {
        id: 2,
        name: '时间',
        type: 'time',
      },
    ],
    active: 'time',
    list: [
      {
        id: 1,
        author: '刘德华',
        comment: '给我一杯忘情水',
        time: new Date('2021-11-10 09:09:00'),
        img: 'https://y.qq.com/music/photo_new/T001R300x300M000003aQYLo2x8izP.jpg?max_age=2592000',
        // 1: 点赞 0：无态度 -1:踩
        attitude: 1,
      },
      {
        id: 2,
        author: '周杰伦',
        comment: '听妈妈的话',
        time: new Date('2021-10-11 09:09:00'),
        img: 'https://y.qq.com/music/photo_new/T001R500x500M0000025NhlN2yWrP4.jpg?max_age=2592000',
        // 1: 点赞 0：无态度 -1:踩
        attitude: 0,
      },
      {
        id: 3,
        author: '陈奕迅',
        comment: '十年',
        time: new Date('2021-12-11 10:09:00'),
        img: 'https://y.qq.com/music/photo_new/T001R500x500M000003Nz2So3XXYek.jpg?max_age=2592000',
        // 1: 点赞 0：无态度 -1:踩
        attitude: -1,
      },
    ],
  }
  // 子改父
  changeActive = (active) => {
    this.setState({ active })
  }
  changeList = (newObj) => {
    this.setState({ list: [newObj, ...this.state.list] })
  }
  delItem = (id) => {
    // 根据 id 找索引，根据索引删除数据
    /* const newList = [...this.state.list]
    newList.splice(
      newList.findIndex((item) => item.id === id),
      1
    )
    this.setState({ list: newList }) */
    this.setState({ list: this.state.list.filter((item) => item.id !== id) })
  }
  // !#1. 父组件准备方法并传递给子组件
  changeNice = (id, attitude) => {
    // !#3 根据拿到的参数修改数据
    this.setState({
      list: this.state.list.map((item) => {
        if (item.id === id) {
          return {
            ...item,
            attitude,
          }
        } else {
          return item
        }
      }),
    })
  }
  render() {
    const { tabs, active, list } = this.state
    return (
      <div className='App'>
        <div className='comment-container'>
          <div className='comment-head'>
            <span>1 评论</span>
          </div>
          {/* Tab */}
          <Tab tabs={tabs} active={active} changeActive={this.changeActive} />
          {/* Form */}
          <Form changeList={this.changeList} />
          {/* List */}
          {/* #1 把 active 传到 List 组件，目的是根据 active 进行排序 */}
          <List
            list={list}
            active={active}
            delItem={this.delItem}
            changeNice={this.changeNice}
          />
        </div>
      </div>
    )
  }
}
